package developer.算法.二分查找.在排序数组中查找元素第一个和最后一个位置;

import java.util.Arrays;

/**
 * @author zhangyongkang
 * @time 2025/4/2 14:31
 * @description 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 * <p>
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 * <p>
 * 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
 * <p>
 * 示例 1：
 * <p>
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 * 示例 2：
 * <p>
 * 输入：nums = [5,7,7,8,8,10], target = 6
 * 输出：[-1,-1]
 * 示例 3：
 * <p>
 * 输入：nums = [], target = 0
 * 输出：[-1,-1]
 * <p>
 * [5,7,7,8,8,8,8,10]
 */


// 5, 7, 7, 8, 8, 10
public class WeiZhi {

    public static void main(String[] args) {
        Solution3 solution = new Solution3();

        int[] result1 = solution.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8);
        System.out.println(Arrays.toString(result1));

        int[] result = solution.searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6);
        System.out.println(Arrays.toString(result));
    }

    static class Solution3 {
        public int[] searchRange(int[] nums, int target) {
            return new int[]{doSearch(nums, target, true), doSearch(nums, target, false)};
        }

        public int doSearch(int[] nums, int target, boolean isLower) {
            int left = 0;
            int right = nums.length - 1;
            int ans = -1;
            while (left <= right) {
                int midIdx = left + (right - left) / 2;
                int midVal = nums[midIdx];
//1 2 2 2 3 3 3 4 5 | 3
                if (target > midVal) {
                    left = midIdx + 1;
                }
                if (target < midVal) {
                    right = midIdx - 1;
                }
                if (target == midVal) {
                    if (isLower) {
                        right = midIdx - 1;
                    } else {
                        left = midIdx + 1;
                    }
                    ans = midIdx;
                }
            }
            return ans;
        }
    }

    static class Solution {
        public int[] searchRange(int[] nums, int target) {
            return new int[]{search(nums, target, true), search(nums, target, false)};
        }

        public int search(int[] nums, int target, boolean isLower) {
            int left = 0, right = nums.length - 1;
            int ans = -1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                int midVal = nums[mid];
                if (target > midVal) {
                    left = mid + 1;
                }
                if (target < midVal) {
                    right = mid - 1;
                }
                if (target == midVal) {
                    if (isLower) {
                        right = mid - 1;
                    } else {
                        left = mid + 1;
                    }
                    ans = mid;
                }
            }
            return ans;
        }
    }
}
